package com.ruoyi.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ReflectUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Book;
import com.ruoyi.system.domain.Category;
import com.ruoyi.system.domain.vo.CategoryVo;
import com.ruoyi.system.service.IBookService;
import com.ruoyi.system.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 分类Controller
 *
 * @author ruoyi
 * @date 2022-12-08
 */
@RestController
@RequestMapping("/system/category")
public class CategoryController extends BaseController {
    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IBookService bookService;

    /**
     * 查询分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:category:list')")
    @GetMapping("/tree")
    public TableDataInfo tree(Category category) {
        startPage();
        List<Category> list = categoryService.selectCategoryList(category);
        List<CategoryVo> categoryVos = BeanUtil.copyToList(list, CategoryVo.class);
        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("id");
        config.setParentIdKey("parentId");
        config.setNameKey("categoryName");
        config.setDeep(2);
        config.setChildrenKey("children");
        config.setWeightKey("orderNum");

        // 3.转树
        List<Tree<Long>> treeList = TreeUtil.build(categoryVos, 0L, config, ((object, treeNode) -> {
            Field[] fields = ReflectUtil.getFieldsDirectly(object.getClass(), true);
            for (Field field : fields) {
                String fieldName = field.getName();
                Object fieldValue = ReflectUtil.getFieldValue(object, field);
                treeNode.putExtra(fieldName, fieldValue);
            }
        }));
        if (CollUtil.isEmpty(treeList)) {
            return getDataTable(categoryVos);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(treeList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 查询分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:category:list')")
    @GetMapping("/list")
    public TableDataInfo list(Category category) {
        List<Category> list = categoryService.selectCategoryList(category);
        return getDataTable(list);
    }

    /**
     * 导出分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:category:export')")
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Category category) {
        List<Category> list = categoryService.selectCategoryList(category);
        ExcelUtil<Category> util = new ExcelUtil<Category>(Category.class);
        util.exportExcel(response, list, "分类数据");
    }

    /**
     * 获取分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:category:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(categoryService.selectCategoryById(id));
    }

    /**
     * 新增分类
     */
    @PreAuthorize("@ss.hasPermi('system:category:add')")
    @Log(title = "新增分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Category category) {
        List<Category> categories = categoryService.selectCategoryList(new Category().setCategoryName(category.getCategoryName()));
        if (CollUtil.isNotEmpty(categories)) {
            return AjaxResult.error("该分类已经存在了");
        }
        if (BeanUtil.isNotEmpty(category.getParentId())) {
            category.setLevel(2L);
        }
        return toAjax(categoryService.insertCategory(category));
    }

    /**
     * 修改分类
     */
    @PreAuthorize("@ss.hasPermi('system:category:edit')")
    @Log(title = "修改分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Category category) {
        if (BeanUtil.isNotEmpty(category.getParentId())) {
            category.setLevel(2L);
        }
        return toAjax(categoryService.updateCategory(category));
    }

    /**
     * 删除分类
     */
    @PreAuthorize("@ss.hasPermi('system:category:remove')")
    @Log(title = "批量删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<Book> books = bookService.selectBookByCategoryIds(ids);
        return toAjax(categoryService.deleteCategoryByIds(ids));
    }
}
